<template>
  <div class="hv-dashboard-list">
    <div class="hv-dashboard-list-category">
      <div class="hv-dashboard-list-category-header">
        <div>仪表板类别</div>
        <hv-dynamic-icon iconName="SettingOutlined" @click="categoryManageVisible = true" />
      </div>
      <div class="hv-dashboard-list-category-body" v-hv-scrollbar>
        <div
          :class="[
            'hv-dashboard-list-category-item',
            queryParams.dashboardCategoryId === '' ? 'hv-dashboard-list-category-item-select' : '',
          ]"
          @click="queryListByCategory('')"
        >
          全部
        </div>
        <div
          :class="[
            'hv-dashboard-list-category-item',
            item.dashboardCategoryId === queryParams.dashboardCategoryId
              ? 'hv-dashboard-list-category-item-select'
              : '',
          ]"
          v-for="(item, index) in categoryList"
          :key="index"
          @click="queryListByCategory(item.dashboardCategoryId || '')"
        >
          {{ item.dashboardCategoryLabel }}
        </div>
      </div>
    </div>
    <div class="hv-dashboard-list-data">
      <div class="hv-dashboard-list-data-search">
        <a-input-search
          class="hv-dashboard-list-data-search-input"
          v-model:value="queryParams.dashboardTitle"
          placeholder="请输入仪表板标题..."
          enter-button
          @search="query(true)"
        />
        <a-button type="primary" @click="dashboardAdd()">
          <hv-dynamic-icon iconName="PlusOutlined" /> 添加仪表板
        </a-button>
      </div>
      <div
        v-if="dataSource && dataSource.length > 0"
        class="hv-dashboard-list-data-card-box"
        v-hv-scrollbar
      >
        <a-row :gutter="16">
          <a-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="4"
            v-for="(item, index) in dataSource"
            :key="index"
          >
            <div class="hv-dashboard-card">
              <div class="hv-dashboard-card-header">
                <div class="hv-dashboard-card-header-title">
                  {{ item && item.dashboardTitle ? item.dashboardTitle : '-' }}
                </div>
                <div class="hv-dashboard-card-header-acts">
                  <a-dropdown>
                    <hv-dynamic-icon iconName="MenuOutlined" />
                    <template #overlay>
                      <a-menu>
                        <a-menu-item
                          @click="btnClick(btn.name, item.dashboardId)"
                          v-for="(btn, index) in btnList"
                          :key="index"
                        >
                          <hv-dynamic-icon :iconName="btn.icon" /> {{ btn.label }}
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </div>
              </div>
              <div class="hv-dashboard-card-img">
                <img :src="getImg(item.canvasData)" v-hv-error-src="defaultDashboardImg" />
              </div>
            </div>
          </a-col>
        </a-row>
      </div>
      <div class="hv-card-pagination" v-if="dataSource && dataSource.length > 0">
        <a-pagination
          :size="'small'"
          :current="pagination.current"
          :pageSize="pagination.pageSize"
          :total="pagination.total"
          :show-total="pagination.showTotal"
          :page-size-options="pagination.pageSizeOptions"
          :show-size-changer="pagination.showSizeChanger"
          @change="handlePageChange"
          @showSizeChange="handlePageChange"
        />
      </div>
      <div v-else class="hv-dashboard-list-empty">
        <hv-custom-empty />
      </div>
    </div>
    <hv-dashboard-category-manage v-model:visible="categoryManageVisible" @reload="reload()" />
  </div>
</template>

<script lang="ts">
  import { createVNode, defineComponent, onMounted, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import defaultDashboardImg from '@/visual/assets/img/dashboard/default-dashboard.svg?url';
  import { Modal, notification } from 'ant-design-vue';
  import { QuestionCircleOutlined } from '@ant-design/icons-vue';
  import CommonUtil from '@/visual/commons/utils/common-util';
  import DashboardApi from '@/visual/apis/dashboard-api';
  import HttpResultUtil from '@/visual/commons/utils/http-result-util';
  import { dashboardTitle } from '@/visual/configs/dashboard-conifg';
  import { useVisualConfigStore } from '@/visual/stores/visual-config';
  import DashboardCategoryManage from './DashboardCategoryManage.vue';
  import type DashboardCategoryType from '@/visual/commons/types/dashboard-category-type';
  import { useSpinningStore } from '@/visual/stores/spinning';

  export default defineComponent({
    name: 'DashboardList',
    components: {
      HvDashboardCategoryManage: DashboardCategoryManage,
    },
    setup() {
      const router = useRouter();

      const useVisualConfig = useVisualConfigStore();
      const useSpinning = useSpinningStore();

      const categoryList = ref<DashboardCategoryType[]>([]);
      const categoryManageVisible = ref<boolean>(false);

      const dashboardRoot = useVisualConfig.getRoutePath.dashboardRoot;

      const btnList = [
        {
          name: 'dashboardEdit',
          label: '编辑',
          icon: 'edit-outlined',
        },
        {
          name: 'dashboardView',
          label: '查看',
          icon: 'eye-outlined',
        },
        {
          name: 'deleteDashboard',
          label: '删除',
          icon: 'delete-outlined',
        },
      ];

      const dataSource = ref<any[]>([]);

      const queryParams = CommonUtil.queryParamsInit(
        {
          dashboardTitle: '',
          dashboardCategoryId: '',
        },
        {
          pageSize: 36,
          pageSizeOptions: ['36', '48', '60', '80', '100', '150', '200'],
        }
      );

      /**
       * 初始化页面数据
       */
      const initPageData = () => {
        useSpinning.setSpinningVisible(true);
        DashboardApi.initDashboardListData({}).then(
          (res) => {
            useSpinning.setSpinningVisible(false);
            if (HttpResultUtil.isSuccess(res)) {
              categoryList.value = res.data.responseData.dashboardCategoryList;
            } else {
              HttpResultUtil.failureTipMsg(res);
            }
            query();
          },
          () => {
            useSpinning.setSpinningVisible(false);
          }
        );
      };

      /**
       * 查询数据
       */
      const query = (btnQuery = false) => {
        useSpinning.setSpinningVisible(true);
        CommonUtil.queryDataByConditionPaging(
          btnQuery,
          queryParams,
          DashboardApi.queryDashboardPageList,
          dataSource,
          () => {
            useSpinning.setSpinningVisible(false);
          },
          () => {
            useSpinning.setSpinningVisible(false);
          },
          () => {
            useSpinning.setSpinningVisible(false);
          }
        );
      };

      const getImg = (data: any) => {
        if (data) {
          const json = JSON.parse(data);
          return json && json.coverImg ? json.coverImg : defaultDashboardImg;
        } else {
          return defaultDashboardImg;
        }
      };

      /**
       *分页计算
       */
      const pagination = CommonUtil.paginationComputed(queryParams);

      /**
       * 分页参数改变处理
       */
      const handlePageChange = (current: number, size: number) => {
        CommonUtil.paginationChange(
          queryParams,
          {
            current: current,
            pageSize: size,
          },
          query
        );
      };

      const dashboardAdd = () => {
        router.push({ path: dashboardRoot + '/dashboardAdd' });
      };

      //动态按钮处理
      const btnClick = (name: string, id: '') => {
        ({
          dashboardEdit: () => {
            router.push({ path: dashboardRoot + '/dashboardEdit', query: { id } });
          },
          dashboardView: () => {
            router.push({ path: dashboardRoot + '/dashboardView', query: { id } });
          },
          deleteDashboard: () => {
            Modal.confirm({
              title: '确认',
              icon: createVNode(QuestionCircleOutlined),
              content: '您确认要删除吗？',
              onOk() {
                useSpinning.setSpinningVisible(true);
                DashboardApi.deleteDashboardByIds({
                  ids: [id],
                  updateUser: useVisualConfig.getUserInfo.userName,
                  updateUserId: useVisualConfig.getUserInfo.userId,
                }).then(
                  (res) => {
                    useSpinning.setSpinningVisible(false);
                    if (HttpResultUtil.isSuccess(res)) {
                      notification.success({
                        message: '提示',
                        description: res.data.msg,
                      });
                      query();
                    } else {
                      HttpResultUtil.failureTipMsg(res);
                    }
                  },
                  () => {
                    useSpinning.setSpinningVisible(false);
                  }
                );
              },
            });
          },
        }[name]());
      };

      const queryListByCategory = (id: string) => {
        queryParams.value.dashboardCategoryId = id;
        query(true);
      };

      const reload = () => {
        queryParams.value.dashboardTitle = '';
        queryParams.value.dashboardCategoryId = '';
        queryParams.value.pageNum = 1;
        initPageData();
      };

      onMounted(() => {
        initPageData();
      });

      return {
        reload,
        btnClick,
        queryParams,
        pagination,
        dataSource,
        getImg,
        defaultDashboardImg,
        handlePageChange,
        query,
        dashboardAdd,
        btnList,
        dashboardTitle,
        categoryList,
        queryListByCategory,
        categoryManageVisible,
      };
    },
  });
</script>

<style lang="less" scoped>
  @import './DashboardList.less';
</style>
